package com.zzl.study.auth.security.authentication;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: zhangzl
 * @date: 2024/3/12 21:14
 * @version: 1.0
 * @description: 自定义认证主体
 */
@Data
public class CustomPrincipal implements Transfer<User> {

    /**
     * 密码
     */
    private String password;

    /**
     * 用户名
     */
    private String username;

    /**
     * 自定义授权信息集合
     */
    private Set<CustomAuthority> authorities;

    /**
     * 账户是否过期
     */
    private boolean accountNonExpired;

    /**
     * 账户是否锁定
     */
    private boolean accountNonLocked;

    /**
     * 凭证是否过期
     */
    private boolean credentialsNonExpired;

    /**
     * 是否可用
     */
    private boolean enabled;

    @Override
    public User transform() {
        Set<GrantedAuthority> transformAuthorities = this.authorities == null ? new HashSet<>() : this.authorities.stream().map(CustomAuthority::transform).collect(Collectors.toSet());
        String pass = StringUtils.hasText(this.password) ? this.password : "[PROTECTED]";
        return new User(this.username, pass, this.enabled, this.accountNonExpired, this.credentialsNonExpired, this.accountNonLocked, transformAuthorities);
    }

    /**
     * 由Security框架中的用户转换为自定义认证主体
     *
     * @param user Security框架中的用户
     * @return 自定义认证主体
     */
    public static CustomPrincipal reTransform(User user) {
        if (user == null) {
            return null;
        }
        Set<CustomAuthority> transformAuthorities = user.getAuthorities() == null ? new HashSet<>() : user.getAuthorities().stream().map(authority -> {
            CustomAuthority customAuthority = new CustomAuthority();
            customAuthority.setRole(authority.getAuthority());
            return customAuthority;
        }).collect(Collectors.toSet());
        return buildCustomPrincipal(user, transformAuthorities);
    }

    /**
     * 构造自定义认证主体
     *
     * @param user                 Security框架中的用户
     * @param transformAuthorities 自定义授权信息集合
     * @return 自定义认证主体
     */
    private static CustomPrincipal buildCustomPrincipal(User user, Set<CustomAuthority> transformAuthorities) {
        CustomPrincipal customPrincipal = new CustomPrincipal();
        customPrincipal.setUsername(user.getUsername());
        customPrincipal.setPassword(user.getPassword());
        customPrincipal.setAuthorities(transformAuthorities);
        customPrincipal.setAccountNonExpired(user.isAccountNonExpired());
        customPrincipal.setAccountNonLocked(user.isAccountNonLocked());
        customPrincipal.setCredentialsNonExpired(user.isCredentialsNonExpired());
        customPrincipal.setEnabled(user.isEnabled());
        return customPrincipal;
    }

}
